#include <iostream>
#include <iostream>
#include <vector>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
using namespace std;

class TextQuery{
public:
    void readFile(const string &filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr << "this file is not found" << endl;
            return;
        }
        string line;
        int lineNumber=0;
        while(getline(ifs,line)){
            ++lineNumber;
            _lines.push_back(line);
            istringstream iss(line);
            string word;
            while(iss>>word){
                _wordLineNumbers[word].insert(lineNumber);
                ++_wordCount[word];
            }
        }

    }

    void query(const string &word){
        cout << "===============" << endl;
        cout << word << "occurs" << _wordCount[word] << "times." << endl;
        for(auto &number : _wordLineNumbers[word]){
            cout << "(line" << number << ")" << _lines[number-1] << endl;
        }
        cout << "===============" << endl;
    }


private:
    //存储每行信息
    vector<string> _lines;
    //每个单词和对应的行号的映射关系
    map<string,set<int>> _wordLineNumbers;
    //每个单词以及对应的次数
    map<string,int> _wordCount;
};

void test(){
    string queryword("the");

    TextQuery tq;
    tq.readFile("china_daily.txt");
    tq.query(queryword);

}

int main()
{
    test();
    return 0;
}

